<?php

class Cart {
    static protected $ins = null;
    protected $basket = array();
    
    protected function __construct() {
    }
	
    // 获取购物车对象
    static protected function getIns() {
        if(self::$ins == null) {
            self::$ins = new self();
        }

        return self::$ins;
    }
	
    // 获取购物车
    static public function getCart() {
        // 如果session['cart']不存在,或者存在但不是cart类的实例
        if(!isset($_SESSION['cart']) || !($_SESSION['cart'] instanceof self)) {
            $_SESSION['cart'] = self::getIns();
        }

        return $_SESSION['cart'];
    }

    // 添加商品到购物车
    // 有商品名称,商品id,商品本店价格,购买数量
    public function addItem($id,$name,$shop_price,$num) {
        if(!$this->hasItem($id)) {
            $this->basket[$id] = array('name'=>$name,'shop_price'=>$shop_price,'num'=>$num);
        } else {
            $this->basket[$id]['num'] += $num;
        }
    }

    // 删除商品
    public function delItem($id) {
        if($this->hasItem($id)) {
            unset($this->basket[$id]);
        }
    }

    // 判断某商品是否存在
    public function hasItem($id) {
        return array_key_exists($id,$this->basket);
    }

    // 修改商品数量
    public function modItem($id,$num) {
        if($num == 0) {
            $this->delItem($id);
            return;
        }

        if($this->hasItem($id)) {
            $this->basket[$id]['num'] = $num;
        }
    }

    // 商品加1
    public function incItem($id) {
        if($this->hasItem($id)) {
            $this->basket[$id]['num'] += 1;
        }
    }

    // 商品-1
    public function decItem() {
        if($this->hasItem($id)) {
            $this->basket[$id]['num'] -= 1;
        }
        
        // 要是减到0了,则删掉
        if($this->basket[$id]['num'] == 0) {
            $this->delItem($id);
        }
    }

    // 计算商品种类
    public function cnt() {
        return count($this->basket);
    }
    
    // 返回商品列表
    public function items() {
        return $this->basket;
    }

    // 计算商品的个数
    public function getCount() {
        if($this->cnt() == 0) {
            return 0;
        }

        $count = 0;
        foreach($this->basket as $v) {
            $count += $v['num'];
        }

        return $count;
    }

    // 计算商品的总价格
    public function getPrice() {
        if($this->cnt() == 0) {
            return 0;
        }

        $price = 0;
        foreach($this->basket as $v) {
            $price += $v['num'] * $v['shop_price'];
        }

        return $price;
    }

    // 清空购物车
    public function clear() {
        $this->basket = array();
    }
    
	// 修改商品数量
    public function set($k, $v){
    	$this->basket[$k]['num'] = $v;
    	return true;
    }
    
}
